package com.example.administrator.foodrowfresh.fragmentframework;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.example.administrator.foodrowfresh.R;
import com.example.administrator.foodrowfresh.adapter.HomepageBodyListViewAdapter;
import com.example.administrator.foodrowfresh.adapter.TimeLimitRecyclerAdapter;
import com.example.administrator.foodrowfresh.adapter.ViewPagerAdapter;
import com.example.administrator.foodrowfresh.classfile.JsonParserHomePage;
import com.example.administrator.foodrowfresh.models.HomepageBody;
import com.example.administrator.foodrowfresh.models.TimeLimit;
import com.example.administrator.foodrowfresh.transformer.AccordionTransformer;
import com.example.administrator.foodrowfresh.configs.HomepageConfig;
import com.example.administrator.foodrowfresh.models.TopViewpage;
import com.example.administrator.foodrowfresh.superBase.MyBaseCallBack;
import com.example.administrator.foodrowfresh.superBase.MyBaseFragment;
import com.example.administrator.foodrowfresh.transformer.ViewPagerScroller;
import com.example.administrator.foodrowfresh.views.CitySelect;
import com.example.administrator.foodrowfresh.views.FirstTopSeek;
import com.handmark.pulltorefresh.library.PullToRefreshListView;


import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by Administrator on 2016/4/30.
 */
public class Homepage extends MyBaseFragment implements View.OnClickListener, Handler.Callback {

    private View mView;
    private View headerView;
    private Button firstTopSeekBtn, citySelectBtn;
    //轮播图model数据
    private List<TopViewpage> mCarouselMap;
    //轮播图片
    private ViewPager mViewPager;
    private LinearLayout mDotLayout;
    private ViewPagerAdapter mViewPagerAdapter;
    private Handler mMyHandler;

    //限时抢购
    private RecyclerView mRecyclerView;
    private List<TimeLimit.DataBean.FlashSaleBean> flashSaleBeans;
    private TimeLimitRecyclerAdapter recyclerAdapter;
    private RecyclerView.LayoutManager layoutManager;

    //首页主页面内容
    private PullToRefreshListView refreshListView;
    private List<HomepageBody> dataBeanList;
    private HomepageBodyListViewAdapter listViewAdapter;

    @Override
    public View initView() {
        mView = LayoutInflater.from(getActivity()).inflate(R.layout.layout_homepage_fm, null, false);
        refreshListView= (PullToRefreshListView) mView.findViewById(R.id.pulltorefreshlistview_homepage);
        ListView lv=refreshListView.getRefreshableView();

        headerView=LayoutInflater.from(getActivity()).inflate(R.layout.layout_homepage_header,null,false);

        mViewPager = (ViewPager) headerView.findViewById(R.id.viewPager);
        //动画配置
        AccordionTransformer transformer = new AccordionTransformer();
        mViewPager.setPageTransformer(true, transformer);
        ViewPagerScroller scroller = new ViewPagerScroller(getActivity());
        try {
            Field mScroller = ViewPager.class.getDeclaredField("mScroller");
            mScroller.setAccessible(true);
            mScroller.set(mViewPager, scroller);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //顶部导航，轮播
        mDotLayout = (LinearLayout) headerView.findViewById(R.id.dot_layout);
        //限时抢购
        mRecyclerView = (RecyclerView) headerView.findViewById(R.id.timelimit_RecyclerView);

        //顶部导航
        firstTopSeekBtn = (Button) mView.findViewById(R.id.firstTopSeek_id);
        citySelectBtn = (Button) mView.findViewById(R.id.citySelect);
        firstTopSeekBtn.setOnClickListener(this);
        citySelectBtn.setOnClickListener(this);

        mMyHandler = new Handler(this);

        //给pulltorefreshlistview添加头视图，必须绑定adapter后才显示
        lv.addHeaderView(headerView);
        initData();
        return mView;
    }

    @Override
    public void initData() {
        //图片轮播
        mCarouselMap = new ArrayList<>();
        //限时抢购
        flashSaleBeans = new ArrayList<>();
        //首页内容
        dataBeanList=new ArrayList<>();

        //轮播下载文本
        downloadText(HomepageConfig.CAROUSEL_PATH, HomepageConfig.TYPE_JSON_carousel);
        //下载限时抢购
        downloadText(HomepageConfig.TIMELIMIT_PATH, HomepageConfig.TYPE_JSON_timelimit);
        //下载首页内容
        downloadText(HomepageConfig.HOMEPAGEBODY_PATH,HomepageConfig.TYPE_JSON_BODY);

        //配置ViewPager适配器
        mViewPagerAdapter = new ViewPagerAdapter(mCarouselMap, getActivity());
        mViewPager.setAdapter(mViewPagerAdapter);

        //限时抢购配置适配器
        layoutManager=new LinearLayoutManager(getActivity(),LinearLayoutManager.HORIZONTAL,true);
        recyclerAdapter=new TimeLimitRecyclerAdapter(flashSaleBeans,getActivity());
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(recyclerAdapter);

        //主页内容绑定适配器
        listViewAdapter=new HomepageBodyListViewAdapter(dataBeanList,getActivity());
        refreshListView.setAdapter(listViewAdapter);

        //默认在1亿多
        if (mCarouselMap.size() > 0) {
            mViewPager.setCurrentItem(Integer.MAX_VALUE / 2 - ((Integer.MAX_VALUE / 2) % mCarouselMap.size()));
        }
        //3秒定时
        mMyHandler.sendEmptyMessageDelayed(0, 3000);
        updateIntroAndDot();
    }

    /*
    * 下载文本
    * */
    private void downloadText(String pathText, final int type) {
        getData(pathText, new MyBaseCallBack() {
            @Override
            public void onStart() {
            }

            @Override
            public void onResult(String result) {
                if (HomepageConfig.TYPE_JSON_carousel == type) {
                    //下载轮播数据json解析
                    if (result != null) {
                        List<TopViewpage> list = JsonParserHomePage.parserJsonTopViewpage(result);
                        mCarouselMap.addAll(list);
                    }
                    initDots();
                    mViewPagerAdapter.notifyDataSetChanged();
                }else if (HomepageConfig.TYPE_JSON_timelimit == type) {
                    //限时抢购
                    if (result!=null)
                    {
                        List<TimeLimit.DataBean.FlashSaleBean> list = JsonParserHomePage.parserJsonTimeLimit(result);
                        flashSaleBeans.addAll(list);
                    }
                    recyclerAdapter.notifyDataSetChanged();
                }else if (HomepageConfig.TYPE_JSON_BODY==type)
                {
                    //首页内容
                    if (result!=null)
                    {
                        List<HomepageBody> list=JsonParserHomePage.parserJsonHomepageBody(result);
                        dataBeanList.addAll(list);
                        listViewAdapter.notifyDataSetChanged();
                    }
                }
            }

            @Override
            public void onError() {
            }

            @Override
            public void onFinish() {
            }
        });
    }

    /*
    * 顶部跳转
    * */
    public void onClick(View view) {
        Intent intent = new Intent();
        if (view != null) {
            switch (view.getId()) {
                case R.id.firstTopSeek_id:
                    intent.setClass(getActivity(), FirstTopSeek.class);
                    break;

                case R.id.citySelect:
                    intent.setClass(getActivity(), CitySelect.class);
                    break;
            }
            startActivity(intent);
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1);
        mMyHandler.sendEmptyMessageDelayed(0, 3000);
        return false;
    }

    /**
     * 初始化dot
     */
    private void initDots() {
        for (int i = 0; i < mCarouselMap.size(); i++) {
            View view = new View(getActivity());
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(8, 8);
            if (i != 0) {
                //第一个点不需要左边距
                params.leftMargin = 5;
            }
            view.setLayoutParams(params);
            view.setBackgroundResource(R.drawable.selector_dot);
            mDotLayout.addView(view);
        }
    }

    /**
     * 更新文本
     */
    private void updateIntroAndDot() {
        if (mCarouselMap.size() > 0) {
            int currentPage = mViewPager.getCurrentItem() % mCarouselMap.size();
            for (int i = 0; i < mDotLayout.getChildCount(); i++) {
                mDotLayout.getChildAt(i).setEnabled(i == currentPage);//设置setEnabled为true的话 在选择器里面就会对应的使用白色颜色
            }
        }

    }
}
